package com.region.integral.common_user.consume.dao.impl;

import java.util.List;

import org.springframework.stereotype.Component;

import com.region.integral.common_user.consume.dao.IExchangeK;
import com.region.integral.common_user.obtain.vo.IntegralData;
import com.region.integral.common_user.pojo.CUIEntity;
import com.region.integral.common_user.pojo.KCurrencyEntity;
import com.region.integral.common_user.xml.Regulation;
import com.region.integral.common_user.xml.dto.ExchangeK;
import com.region.integral.exception.IntegralException;
import com.region.integral.hibernate.BaseHibernate;
import com.region.integral.util.CommonUserLogUtil;
import com.region.integral.util.XMLRegulationUtil;
@Component("iExchangeK")
public class ExchangeKImpl extends BaseHibernate implements IExchangeK {

	@Override
	public void exchangeK(int userid,int KexchangeNum, IntegralData integralData) throws IntegralException {

		CUIEntity cuiEntity = getCUIEntity(userid);
		if (cuiEntity != null) {
			int currIntegral = cuiEntity.getCurrIntegral();
			
			Regulation regulation = XMLRegulationUtil.unmarshaller();
			List<ExchangeK> exchangeKs = regulation.getExchangek();
			for (ExchangeK exchangeK : exchangeKs) {
				int ruleIntegral = exchangeK.getIntegral();
				int exchangeIntegral = KexchangeNum * ruleIntegral;
				if(currIntegral >= Math.abs(exchangeIntegral)){
					int totalIntegral = currIntegral + exchangeIntegral;
					cuiEntity.setCurrIntegral(totalIntegral);
					KCurrencyEntity kcEntity = cuiEntity.getkCurrency();
					int maxKCurrency = kcEntity.getMaxKCurrency();
					int currk = kcEntity.getKcurrency();
					kcEntity.setKcurrency(currk+KexchangeNum);
					if (maxKCurrency < (currk+KexchangeNum)) {
						kcEntity.setMaxKCurrency(currk+KexchangeNum);
					}
					cuiEntity.setkCurrency(kcEntity);
					hibernateTemplate.update(cuiEntity);
					hibernateTemplate.save(CommonUserLogUtil.log(userid, exchangeIntegral, "exchangeK"));
					hibernateTemplate.save(CommonUserLogUtil.log(userid, KexchangeNum, "exchangeK_k"));
					integralData.setSuccee(true);
				}
				else{
					integralData.setSuccee(false);
				}
			}
			
		}
		
	}

}
